package ua.kiev.tosik.price.modules.search.conf;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ua.kiev.tosik.price.conf.AppConfig;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class FilterConfig {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.search.conf");
	private final String configFile = "filters.xml";
	private List<IFilter> filters;
	private InputStream is;
	private String lang;

	public FilterConfig() {
		logger.debug("Initialize FilterConfig");
		filters = new ArrayList<IFilter>();
		lang = AppConfig.getInstance().get("app.language");
		try {
			is = getClass().getResource(configFile).openStream();
			loadFilters(is);
			is.close();
			logger.debug("Found " + filters.size() + " filter(s)");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public List<IFilter> getFilters() {
		return filters;
	}

	private void loadFilters(InputStream is) throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(is);
		doc.getDocumentElement().normalize();
		NodeList nodeLst = doc.getElementsByTagName("filter");
		for (int i = 0; i < nodeLst.getLength(); i++) {
			Node fstNode = nodeLst.item(i);
			if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
				NodeList name = ((Element)fstNode).getElementsByTagName("name-" + lang);
				NodeList className = ((Element)fstNode).getElementsByTagName("class");
				try {
					Class clazz = Class.forName(className.item(0).getTextContent());
					IFilter filter = (IFilter)clazz.getConstructor().newInstance();
					filter.setName(name.item(0).getTextContent());
					filters.add(filter);
				} catch (Exception e) {
					logger.warn(e);
				}
			}
		}
	}

}
